#!/usr/bin/evn python3
# -*- coding: utf-8 -*-
from pydub import AudioSegment
from pydub.silence import split_on_silence
from tkinter import *
import sys
import os
from readLrc import readlrc,toStandardLrc
from audio_play2 import AudioPlay
from pathlib import Path
from utils.oss_util import bucket,httpBaseUrl
from utils.laypage import Laypage
from utils.anki_manage import AnkiManag e
import urllib.parse
import tkinter.messagebox #这个是消息框，对话框的关键

# 替换main函数中的两个路径，自动创建anki音频，上传至自己的oss，开源前记得换掉oss账号
# http://www.kekenet.com/cet4/tl/
# 发现了获取字幕的好办法lrc。可可英语网站中的公共js变量

#带后缀的将处理文件名
audioName=""

#anki info
deckName="4听力"
modelName="英语听力"


def testMediaPlay(song):
    root = Tk()
    root.geometry('500x500') # 这里的*必须用小写x
    play = AudioPlay(song)
    buttonStart = Button(root, text="play", width="10",command=play.play)
    buttonStart.grid(row=0,column=0)
    buttonStop = Button(root, text="stop", width="10", command=play.stop)
    buttonStop.grid(row=0,column=1)
    root.mainloop()
# 在每一段音频切割前加空腔1秒


def uploadOssAndAnki(sentence):
    global audioName
    global deckName
    global modelName

    #文件名_startTime_endTime_endTime
    fileName= Path(audioName).stem+"_"+str(sentence["startTime"])+"_"+str(sentence["endTime"])+""+Path(audioName).suffix
    # 编码并保存到本地先
    sentence["audioData"].export("chunks\\"+fileName);
    # 上传到阿里云
    htppFileName = os.path.join("english/audio/", fileName)
    res=bucket.put_object_from_file(htppFileName, "chunks\\" + fileName)
    if(res.status!=200):
        tkinter.messagebox.showerror('警告', '上传oss失败')
    # 添加到anki
    print(res)
    # 拼接音频播放url
    audioHttpUrl=httpBaseUrl+urllib.parse.quote(htppFileName)
    enText = sentence["en"]
    chText = sentence["ch"]
    tags=[Path(audioName).stem]
    AnkiManage.addNote(deckName,modelName,{"audio":audioHttpUrl,"sentence":enText,"translation":chText},tags)
    tkinter.messagebox.showinfo('提示', '制卡成功')


def createNextPage(root,audioPlay,song,sentences):
    if(sentences==[]):
        return
    for i, value in enumerate(sentences):
        time_text = Text(root, width=100, height=3, foreground="green")
        time_text.grid(row=i, column=0, sticky="nw", pady=5)
        time_text.insert(END, value["en"] + "\n" + value["ch"])
        startTime = value["startTime"]
        endTime = value["endTime"] if value["endTime"] != -1 else len(song)
        # 按钮点击就播放一部分音乐
        audioData = song[startTime:endTime]
        # 将切割好的音乐加入实体
        value["audioData"] = audioData

        btn_open = Button(root, text="play", width=10, command=lambda data=audioData: audioPlay.play(data))
        btn_open.grid(row=i, column=1)
        btn_createNote = Button(root, text="addNote", width=10,
                                command=lambda sentence=value: uploadOssAndAnki(sentence))
        btn_createNote.grid(row=i, column=2)

def createUI(song,sentences):
    laypage = Laypage(sentences,8)
    root = Tk()
    root.title('anki quick')
    audioPlay = AudioPlay(song)

    createNextPage(root,audioPlay,song,laypage.nextList())

    lastPage = Button(root, text="lastPage", width=10,
                            command=lambda laypage=laypage: createNextPage(root, audioPlay, song, laypage.lastList()))
    lastPage.grid();
    nextPage = Button(root, text="nextPage", width=10,
                            command=lambda laypage=laypage: createNextPage(root,audioPlay,song,laypage.nextList()))
    nextPage.grid();
    root.mainloop()
    # 关闭声音播放
    audioPlay.stop()



def main():
    mp3Path = r'C:\Users\19135\Desktop\四级\听力素材\2021年6月英语四级听力真题 短文(3).mp3'
    global audioName
    audioName= os.path.basename(mp3Path)
    if not os.path.exists('./chunks'): os.mkdir('./chunks')
    # 载入
    song = AudioSegment.from_mp3(mp3Path)
    # song = song[:1000*10]
    # song.export('./chunks/'+"test_split.mp3")
    #[(startTime,endTime,enText,chText),()...(999,-1,english,chinese)]
    # 读取歌词文件信息
    lrc_arr=[
    {
        "id": "4798505",
        "news_id": "636354",
        "order": "1",
        "start": 0,
        "end": "",
        "en": "In cold and snowy Alaska, there's a village called Takotna. It has a population of mere 49 adults.",
        "cn": "在寒冷多雪的阿拉斯加，有一个名为塔克哈纳的村庄。该村庄只有49个人。"
    },
    {
        "id": "4798506",
        "news_id": "636354",
        "order": "2",
        "start": 9.04,
        "end": "",
        "en": "Each March, this tiny village swells up in numbers because it is located in the middle of a race that takes place every year.",
        "cn": "每年三月，这座小村庄会人满为患，因为其位于每年举行的比赛赛段的中间地点。"
    },
    {
        "id": "4798507",
        "news_id": "636354",
        "order": "3",
        "start": 18.75,
        "end": "",
        "en": "It is a seven-day race called \"The Iditarod Trail\". And participants stop at Takotna for the obligatory 24 hour rest.",
        "cn": "这是一场为期七天的比赛，名为“艾迪塔罗德狗拉雪橇比赛”。参与者会在塔克哈纳停留24小时休息。"
    },
    {
        "id": "4798508",
        "news_id": "636354",
        "order": "4",
        "start": 29.42,
        "end": "",
        "en": "Lucky for them, Takotna is famous for its delicious fruit pies.",
        "cn": "幸运的是，塔克哈纳以其美味的水果馅饼而闻名。"
    },
    {
        "id": "4798509",
        "news_id": "636354",
        "order": "5",
        "start": 35.47,
        "end": "",
        "en": "Weeks before the competitors arrive, the residents of Takotna start preparing what is without question their biggest event of the year.",
        "cn": "在参赛者到来的几周前，塔科特纳的居民们就开始为这一年最大的活动做准备。"
    },
    {
        "id": "4798510",
        "news_id": "636354",
        "order": "6",
        "start": 45.18,
        "end": "",
        "en": "The whole village chips in to help, including the kids, who end up developing their baking skills at an early age.",
        "cn": "全村的人都会来帮忙，孩子们也在其中，他们在很小的时候就发展了烘焙技能。"
    },
    {
        "id": "4798511",
        "news_id": "636354",
        "order": "7",
        "start": 53.3,
        "end": "",
        "en": "Exhausted and hungry racers are greeted with delightful pies of all kinds, such as apple, orange, lemon, or banana.",
        "cn": "疲惫不堪、饥肠辘辘的选手会得到各种令人愉快的馅饼，如苹果、橘子、柠檬或香蕉。"
    },
    {
        "id": "4798512",
        "news_id": "636354",
        "order": "8",
        "start": 63.98,
        "end": "",
        "en": "They consume the pies and a stomach warming race fuel.",
        "cn": "他们吃馅饼和暖胃的比赛食物。"
    },
    {
        "id": "4798513",
        "news_id": "636354",
        "order": "9",
        "start": 68.95,
        "end": "",
        "en": "The toughness of the race allows for racers to eat pretty much whatever they want. The more calories, the better.",
        "cn": "比赛的激烈程度使选手们可以想吃什么就吃什么。卡路里越多越好。"
    },
    {
        "id": "4798514",
        "news_id": "636354",
        "order": "10",
        "start": 76.53,
        "end": "",
        "en": "Takotna has gained a reputation for its dessert-based hospitality since the 1970s.",
        "cn": "自上世纪70年代以来，塔克哈纳就以甜点招待而闻名。"
    },
    {
        "id": "4798515",
        "news_id": "636354",
        "order": "11",
        "start": 83.49,
        "end": "",
        "en": "It started with one person, Jane Newton. Jane moved from Iditarod with her husband in 1972 and opened a restaurant.",
        "cn": "这始于简·牛顿。1972年，简和丈夫从伊迪塔罗德搬来，开了一家餐馆。"
    },
    {
        "id": "4798516",
        "news_id": "636354",
        "order": "12",
        "start": 93.97,
        "end": "",
        "en": "A rich and filling fruit pies quickly got the races attention, and the village gained some fame as a result.",
        "cn": "一种馅料丰富且丰盛的水果馅饼很快引起了赛事的注意，村庄也因此名声大噪。"
    },
    {
        "id": "4798517",
        "news_id": "636354",
        "order": "13",
        "start": 101.81,
        "end": "",
        "en": "Proud residents then started to refer to Jane as queen of Takotna.",
        "cn": "骄傲的居民开始称简为塔克哈纳女王。"
    },
    {
        "id": "4798518",
        "news_id": "636354",
        "order": "14",
        "start": 107.89,
        "end": "",
        "en": "Questions 22 to 25 are based on the passage you have just heard.",
        "cn": "请根据刚才所听文章回答22至25题。"
    },
    {
        "id": "4798519",
        "news_id": "636354",
        "order": "15",
        "start": 114.19,
        "end": "",
        "en": "Q22. Why do a lot of people come to the village of Takotna every March?",
        "cn": "问题22. 为什么每年三月都有很多人来塔克哈纳村？"
    },
    {
        "id": "4798520",
        "news_id": "636354",
        "order": "16",
        "start": 132.58,
        "end": "",
        "en": "Q23. What is the village of Takotna famous for?",
        "cn": "问题23. 塔克哈纳村以什么闻名？"
    },
    {
        "id": "4798521",
        "news_id": "636354",
        "order": "17",
        "start": 147.66,
        "end": "",
        "en": "Q24. Who comes to help with the event of the year?",
        "cn": "问题24. 谁来帮忙准备年度盛事？"
    },
    {
        "id": "4798522",
        "news_id": "636354",
        "order": "18",
        "start": 163.99,
        "end": "",
        "en": "Q25. What does the passage say about Jane Newton?",
        "cn": "问题25. 这篇文章如何描述简·牛顿？"
    }
    ]
    sentences =toStandardLrc(lrc_arr)

    # testMediaPlay(song)
    createUI(song,sentences)




if __name__ == '__main__':
    main()

